﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EasyTemplates
{
    public class Template
    {
        public Template() {}

        // parametersAndValues are sandwich (parameter name, parameter value):
        // Typical call would be:
        //  new Template(
        //        templateBody,
        //        "Param1", value1,
        //        "Param2", value2
        //  ).Generate()
        public Template(
            string templateBody,
            params object[] parametersAndValues 
        )
        {
            TemplateBody = templateBody;
            for (int ndxParamCrt = 0;
                 ndxParamCrt < parametersAndValues.Length;
                 ndxParamCrt += 2)
            {
                string name = parametersAndValues[ndxParamCrt] as string;
                object value = parametersAndValues[ndxParamCrt + 1];

                if (value == null)
                    Debug.WriteLine(
                        String.Format(
                            "Warning: Parameter {0} is null - type object will be used",
                            name
                        )
                    );

                Parameters.Add(
                    name,
                    new Parameter(value)
                );
            }
        }

        public TemplateLanguages Language { get; set; }

        public string TemplateBody { get; set; }

        Dictionary<string, Parameter> parameters = new Dictionary<string, Parameter>();
        public Dictionary<string, Parameter> Parameters
        {
            get { return parameters; }
        }

        ITemplateCompiler templateCompiler = new TypeGeneratorCache();
        public string Generate()
        {
            templateCompiler.Template = this;

            Type templateGenerator = templateCompiler.GenerateType();

            GeneratedTemplate generatedTemplate = Activator.CreateInstance(templateGenerator) as GeneratedTemplate;
            generatedTemplate.Template = this;

            return generatedTemplate.Generate();
        }
    }
}
